package vv.lines.core;

import vv.lines.core.context.IContext;
import vv.lines.view.BallView;
import vv.lines.view.View;

/**
 *
 * @author vpotapenko
 */
public class Ball extends AbstractFieldItem {

    private int value;
    private Cell owner;
    private boolean selected;

    public Ball(IContext context, int value) {
        super(context);
        this.value = value;
        
        setZOrder(1);
        getView().setColor(value);
    }

    public Cell getOwner() {
        return owner;
    }

    public void setOwner(Cell cell, boolean update) {
        this.owner = cell;

        if (update) updateBounds();
    }

    public int getValue() {
        return value;
    }

    @Override
    public BallView getView() {
        return (BallView) super.getView();
    }

    public boolean sameValue(Ball ball) {
        return ball != null && value == ball.value;
    }

    public void updateBounds() {
        if (owner == null) return;

        setLocation(owner.getX(), owner.getY());
        setSize(owner.getWidth(), owner.getHeight());
    }

    void setSelected(boolean b) {
        this.selected = b;
        getView().setSelected(b);

        handleChangeSelection();
    }

    private void handleChangeSelection() {
        if (selected) setZOrder(2);
        else setZOrder(1);
    }

    public void setAlpha(float alpha) {
        BallView view = getView();
        if (view != null) view.setAlpha(alpha);
    }

    @Override
    protected View createView() {
        BallView view = getViewFactory().createBallView(this);
        view.setColor(value);

        return view;
    }

    public void handleAction(ActionId type) {
        getField().dispatchBallSelection(this);
    }
}
